<?php

class Default_IndexController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function preDispatch() {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $action = $this->_request->getActionName();
            /* if ($action != 'login' && $action == 'registry') {
              $this->_redirect('/index/registry');
              return;
              } */
            /* if ($action != 'login' && $action != 'registry') {
              $this->_redirect('/index/login');
              return;
              } */
            /* if ($action != 'registry') {
              $this->_redirect('/index/registry');
              return;
              } */
        }
    }

    public function editAction() {
        if ($this->_request->isPost()) {
            $tbUsers = new Default_Model_Users();
            $userId = $_SESSION['user1'];
            $password = htmlspecialchars($this->_getParam('prdPassword'));
            $fullName = htmlspecialchars($this->_getParam('txtFullName'));
            $address = htmlspecialchars($this->_getParam('txtAddress'));
            $phone = htmlspecialchars($this->_getParam('txtPhone'));
            $email = htmlspecialchars($this->_getParam('txtEmail'));
            $photo = htmlspecialchars($this->_getParam('txtPhoto'));

            $data = array('Password' => $password,
                'FullName' => $fullName,
                'Address' => $address,
                'Phone' => $phone,
                'Email' => $email,
                'Photo' => $photo);
            $tbUsers->update($data, "UserId = '$userId'");
            //$this->view->status = "Đã sửa xong, cám ơn!";
            $this->goHome();
        }
        else
            $this->view->status = "Chỉnh sửa thông tin!";
    }

    public function deleteAction() {
        // Xoa noi dung chat
        $user1 = $_SESSION['user1'];
        $user2 = $_SESSION['user2'];
        $tbContents = new Default_Model_Contents();
        $cond = "(UserId1 = '$user1' and UserId2 = '$user2')";
        $tbContents->delete($cond);
        $this->goHome();
    }

    public function registryAction() {
        $tbUsers = new Default_Model_Users();
        $userId = htmlspecialchars($this->_getParam('txtUserId'));
        $password = htmlspecialchars($this->_getParam('prdPassword'));
        if ($userId != "") {
            // Kiem tra xem UserId co ton tai khong
            $users = $tbUsers->fetchAll("UserId = '$userId'")->toArray();
            if ($users == NULL) {
                $fullName = htmlspecialchars($this->_getParam('txtFullName'));
                $address = htmlspecialchars($this->_getParam('txtAddress'));
                $phone = htmlspecialchars($this->_getParam('txtPhone'));
                $email = htmlspecialchars($this->_getParam('txtEmail'));
                $photo = htmlspecialchars($this->_getParam('txtPhoto'));

                $data = array('UserId' => $userId,
                    'Password' => $password,
                    'FullName' => $fullName,
                    'Address' => $address,
                    'Phone' => $phone,
                    'Email' => $email,
                    'Photo' => $photo,
                    'TimeOnline' => 0,
                    'TimeOffline' => 0,
                    'IsOnline' => '0',
                    'IsActive' => '0',
                    'IsAdmin' => '0');
                $tbUsers->insert($data);
                $this->view->status = "Đã tạo xong, cám ơn bạn đã tham gia!";
            }
            else
                $this->view->status = "UserId đã tồn tại, hãy chọn tên khác!";
        }
        else
            $this->view->status = "UserId không thể rỗng!";
    }

    public function storyAction() {
        $tbStorys = new Default_Model_Storys();
        $count = $tbStorys->fetchAll()->count() + 2;
        $title = htmlspecialchars($this->_getParam('txtTitle'));
        $category = htmlspecialchars($this->_getParam('txtCategory'));
        $content = htmlspecialchars($this->_getParam('txtContent'));

        if ($title != "" && $category && $content) {
            $data = array('StoryId' => $count,
                'Title' => $title,
                'Category' => $category,
                'Content' => $content,
                'PostTime' => $this->toDay(),
                'Author' => $_SESSION['user1']);
            $tbStorys->insert($data);
            $this->view->status = "Đã lưu xong, cám ơn bạn đã đóng góp!";
            $this->goHome();
        }
        else
            $this->view->status = "Dữ liệu không thể rỗng!";
    }

    public function rstoryAction() {
        /* $tbStorys = new Default_Model_Storys();
          $storys =$tbStorys->fetchAll();
          $this->view->storys = $storys->toArray();
          $this->view->totalRecord = $storys->count(); */
    }

    public function indexAction() {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect('/index/login');
        }
        $users = $auth->getIdentity();
        $user1 = $users->UserId;
        $this->view->fullName1 = $users->FullName;

        $user2 = $_SESSION['user2'];
        $this->view->user2 = $user2;
        $this->view->user1 = $user1;
        $this->view->loginTime = $_SESSION['loginTime'];

        $tb_Users = new Default_Model_Users();
        $users = $tb_Users->fetchAll("UserId = '$user2'")->toArray();
        $this->view->fullName2 = $users[0]['FullName'];
        // Đọc nội dung đưa lên form
        $tbContents = new Default_Model_Contents();
        $cond1 = "(UserId1 = '$user1' and UserId2 = '$user2')";
        $cond2 = "(UserId1 = '$user2' and UserId2 = '$user1')";
        $this->view->contents = $tbContents->fetchAll("$cond1 or $cond2", "ContentId desc", 10, 0)->toArray();
    }

    public function saveAction() {
        $auth = Zend_Auth::getInstance();
        if ($this->_request->isPost()) {
            $tbContents = new Default_Model_Contents();
            $send = $this->_getParam('txtSend');
            if ($send != "") {
                $count = $tbContents->fetchAll()->count(); // đếm số mẫu tin
                $data = array('ContentId' => $count + 1,
                    'UserId1' => $_SESSION['user1'],
                    'UserId2' => $_SESSION['user2'],
                    'Content' => $send,
                    'PostTime' => $this->toDay());
                $tbContents->insert($data);
            }
        }
        $this->goHome();
    }

    public function loginAction() {
        $this->view->status = "Chưa đăng nhập!";
        if ($this->_request->isPost()) {
            $prefix = Zend_Registry::get('prefix');
            $db = Zend_Registry::get('cnn'); // 1. Gọi ket noi voi Zend_Db
            $auth = Zend_Auth::getInstance(); // 2. Khoi tao Zend_Auth
            // 3. Khai bao bảng va 2 cot sẽ dùng so sanh trong qua tronh login
            $authAdapter = new Zend_Auth_Adapter_DbTable($db);
            $authAdapter->setTableName($prefix . 'Users')
                    ->setIdentityColumn('UserId')
                    ->setCredentialColumn('Password');

            // 4. Lay gia tri duoc gởi qua tu form
            $uname = $this->_getParam('txtUserId');
            $paswd = $this->_getParam('prdPassword');
            $cwith = $this->_getParam('sctChat');

            // 5. Dua vao so sanh voi du lieu khai bao o muc 3
            $authAdapter->setIdentity($uname);
            $authAdapter->setCredential($paswd);

            //6. Kiem tra trang thai cua user neu Active = 1 moi duoc login
            /* $select = $authAdapter->getDbSelect();
              $select->where('Active = 1'); */

            // 7. Lay ket qua truy van
            $result = $auth->authenticate($authAdapter);
            $flag = false;
            if ($result->isValid()) {
                // 8. Lay nhung du lieu can thiet trong bang Users neu login thanh cong
                $data = $authAdapter->getResultRowObject(null, array('Password'));
                // 9. Luu  nhung du lieu cua member vao session
                $auth->getStorage()->write($data);
                $flag = true;
            }
            if ($flag == true) {
                // Lưu thông tin vao CSDL
                $tbUsers = new Default_Model_Users();
                $today = $this->toDay();
                $_SESSION['loginTime'] = $today;
                $_SESSION['user1'] = $uname;
                $_SESSION['user2'] = $cwith;
                $users = $auth->getIdentity();
                $_SESSION['fullName1'] = $users->FullName;
                $_SESSION['address'] = $users->Address;
                $_SESSION['phone'] = $users->Phone;
                $_SESSION['email'] = $users->Email;
                $_SESSION['photo'] = $users->Photo;
                $data = array('TimeOnline' => $today,
                    'IsOnline' => '1');
                $tbUsers->update($data, "UserId = '$uname'");

                // Xoa noi dung chat
                $tbContents = new Default_Model_Contents();
                $cond = "(UserId1 = '$uname' and UserId2 = '$cwith')";
                $tbContents->delete($cond);
                $this->goHome();
            }
            else
                $this->view->status = "Lỗi, kiểm tra tài khoản và mật khẩu!";
        }
    }

    public function logoutAction() {
        $auth = Zend_Auth::getInstance();
        $users = $auth->getIdentity();
        $auth->clearIdentity();
        $user1 = $_SESSION['user1'];
        $user2 = $_SESSION['user2'];

        $tbUsers = new Default_Model_Users();
        $data = array('TimeOffline' => $this->toDay(),
            'IsOnline' => '0');
        $tbUsers->update($data, "UserId = '$user1'");

        // Xoa noi dung chat
        $tbContents = new Default_Model_Contents();
        $cond = "(UserId1 = '$user1' and UserId2 = '$user2')";
        $tbContents->delete($cond);
        $this->goHome();
    }

    protected function toDay() {
        $today = getdate();
        $today = $today['year'] . '-' .
                $today['mon'] . '-' .
                $today['mday'] . ' ' .
                $today['hours'] . ':' .
                $today['minutes'] . ':' .
                $today['seconds'];
        return $today;
    }

    protected function printArray($data) {
        echo '<pre>';
        print_r($data);
        echo '</pre>';
    }

    protected function noRender() {
        $this->_helper->viewRenderer->setNoRender(TRUE);
    }

    protected function goHome() {
        $this->_redirect("/index/index");
    }

    protected function leoteoAction() {
        $tbLeoTeo = new Default_Model_Leoteos();
        $this->view->nod1 = $tbLeoTeo->fetchAll("Lgo = 1");
        $this->view->nod2 = $tbLeoTeo->fetchAll("Lgo = 2");
        $this->view->nod3 = $tbLeoTeo->fetchAll("Lgo = 3");
        $this->view->nod4 = $tbLeoTeo->fetchAll("Lgo = 4");
        $this->view->nod5 = $tbLeoTeo->fetchAll("Lgo = 5");
        $this->view->nod6 = $tbLeoTeo->fetchAll("Lgo = 6");
        $this->view->nod7 = $tbLeoTeo->fetchAll("Lgo = 7");
    }

    protected function productxAction() {
        $tbProductx = new Default_Model_Productx();
        $this->view->nod = $tbProductx->fetchAll();
    }

    protected function btreeAction() {
        $tbBtree = new Default_Model_Btree();
        $this->view->nod = $tbBtree->fetchAll();
    }
}